package models

import (
	"errors"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"gitee.com/lzqysoft/ga_wz_backend/libs/cache"
	"reflect"
	"strings"
	"time"
)

type ProdType struct {
	Id       string    `orm:"column(id);pk"`
	Name     string    `orm:"column(name)"`
	Pid      string    `orm:"column(pid)"`
	Remark   string    `orm:"column(remark);null"`
	Status   int       `orm:"column(status)"`
	Isdelete int       `orm:"column(isdelete)"`
	Ctime    time.Time `orm:"column(ctime);type(date);type(timestamp with time zone)"`
	Creater  string    `orm:"column(creater);null"`
	Utime    time.Time `orm:"column(utime);type(date);type(timestamp with time zone)"`
	Updater  string    `orm:"column(updater);null"`
}

//Tree 树数据结构
type Tree struct {
	Name     string `json:"title"`
	Id       string `json:"id"`
	Expand   bool   `json:"expand"`
	Checked  bool   `json:"checked"`
	Children []Tree `json:"children"`
}

func (t *ProdType) TableName() string {
	return "yjk_prodtype"
}

func init() {
	orm.RegisterModel(new(ProdType))
}

// AddProdType insert a new ProdType into database and returns
// last inserted Id on success.
func AddProdType(m *ProdType) (id int64, err error) {
	o := orm.NewOrm()
	id, err = o.Insert(m)
	return
}

// GetProdTypeById retrieves ProdType by Id. Returns error if
// Id doesn't exist
func GetProdTypeById(id string) (v *ProdType, err error) {
	o := orm.NewOrm()
	v = &ProdType{Id: id}
	if err = o.Read(v); err == nil {
		return v, nil
	}
	return nil, err
}

// GetAllProdType retrieves all ProdType matches certain condition. Returns empty list if
// no records exist
func GetAllProdType(query map[string]string, fields []string, sortby []string, order []string,
	offset int64, limit int64) (ml []interface{}, err error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(ProdType))
	// query k=v
	for k, v := range query {
		// rewrite dot-notation to Object__Attribute
		k = strings.Replace(k, ".", "__", -1)
		if strings.Contains(k, "isnull") {
			qs = qs.Filter(k, (v == "true" || v == "1"))
		} else {
			qs = qs.Filter(k, v)
		}
	}
	// order by:
	var sortFields []string
	if len(sortby) != 0 {
		if len(sortby) == len(order) {
			// 1) for each sort field, there is an associated order
			for i, v := range sortby {
				orderby := ""
				if order[i] == "desc" {
					orderby = "-" + v
				} else if order[i] == "asc" {
					orderby = v
				} else {
					return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
				}
				sortFields = append(sortFields, orderby)
			}
			qs = qs.OrderBy(sortFields...)
		} else if len(sortby) != len(order) && len(order) == 1 {
			// 2) there is exactly one order, all the sorted fields will be sorted by this order
			for _, v := range sortby {
				orderby := ""
				if order[0] == "desc" {
					orderby = "-" + v
				} else if order[0] == "asc" {
					orderby = v
				} else {
					return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
				}
				sortFields = append(sortFields, orderby)
			}
		} else if len(sortby) != len(order) && len(order) != 1 {
			return nil, errors.New("Error: 'sortby', 'order' sizes mismatch or 'order' size is not 1")
		}
	} else {
		if len(order) != 0 {
			return nil, errors.New("Error: unused 'order' fields")
		}
	}

	var l []orm.Params
	qs = qs.OrderBy(sortFields...)
	if _, err = qs.Limit(limit, offset).Values(&l, fields...); err == nil {
		if len(fields) == 0 {
			for _, v := range l {
				r, err := GetProdTypeById(v["Pid"].(string))
				if err == nil && len(r.Name) > 0 {
					v["Pname"] = r.Name
				} else {
					v["Pname"] = "顶级类型"
				}
				ml = append(ml, v)
			}
		} else {
			// trim unused fields
			for _, v := range l {
				m := make(map[string]interface{})
				val := reflect.ValueOf(v)
				for _, fname := range fields {
					m[fname] = val.FieldByName(fname).Interface()
				}
				ml = append(ml, m)
			}
		}
		return ml, nil
	}
	return nil, err
}

// UpdateProdType updates ProdType by Id and returns error if
// the record to be updated doesn't exist
func UpdateProdTypeById(m *ProdType) (err error) {
	o := orm.NewOrm()
	v := ProdType{Id: m.Id}
	// ascertain id exists in the database
	if err = o.Read(&v); err == nil {
		var num int64
		if num, err = o.Update(m); err == nil {
			fmt.Println("Number of records updated in database:", num)
		}
	}
	return
}

// DeleteProdType deletes ProdType by Id and returns error if
// the record to be deleted doesn't exist
func DeleteProdType(id string) (err error) {
	o := orm.NewOrm()
	v := ProdType{Id: id}
	// ascertain id exists in the database
	if err = o.Read(&v); err == nil {
		var num int64
		if num, err = o.Delete(&ProdType{Id: id}); err == nil {
			fmt.Println("Number of records deleted in database:", num)
		}
	}
	return
}

// SoftDeleteProdType 软删除 ProdType
func SoftDeleteProdType(id string, uname string) (err error) {
	o := orm.NewOrm()
	v := ProdType{Id: id}
	if err = o.Read(&v); err == nil {
		v.Isdelete = 1
		v.Updater = uname
		v.Utime = time.Now()
		_, err = o.Update(&v)
	}
	return
}

//GetTypeSubTree 获取类别的子资源
func GetTypeSubTree(pid string, status int64) (ptypes []ProdType, err error) {
	o := orm.NewOrm()
	ptype := new(ProdType)

	_, err = o.QueryTable(ptype).Filter("Pid", pid).Filter("status", status).Filter("isdelete", 0).OrderBy("Pid").All(&ptypes)

	return
}

//GetProdTypeTree 获取所有产品类别的树
func GetProdTypeTree() []Tree {
	cid := "GetProdTypeTree"
	var trees []Tree
	err := cache.GetCache(cid, &trees)
	if err != nil {
		tree := Tree{
			"顶级目录",
			"0",
			true,
			false,
			nil,
		}
		pid := "0"
		getTyprTreeByPid(pid, &tree)
		trees = append(trees, tree)
		cache_expire, _ := beego.AppConfig.Int("cache_expire")
		cache.SetCache(cid, trees, cache_expire)
	}

	return trees
}

//getTyprTreeByPid 递归获取类别树，根据类别父id，Tree指针返回
func getTyprTreeByPid(pid string, pTree *Tree) {
	typelist, _ := GetTypeSubTree(pid, 1)
	if len(typelist) < 1 {
		return
	}
	for k, v := range typelist {
		dtree := Tree{
			v.Name,
			v.Id,
			true,
			false,
			nil,
		}
		pTree.Children = append(pTree.Children, dtree)
		getTyprTreeByPid(v.Id, &pTree.Children[k])
	}

}
